<template>
  <div class="stations">
    <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom:10px;">
      <el-breadcrumb-item><img style="width: 16px;vertical-align: middle;margin-right: 5px" src="@/assets/indexPage/location.png"/> 场站管理</el-breadcrumb-item>
      <el-breadcrumb-item>
        <span style="font-weight:600;">
          场站信息
        </span>
      </el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-form ref="form" :model="form" class="searchLine">
          <el-form-item label="单位" class="searchItem">
            <!-- <SelectTree ref="orgTree" v-model="form.deptId" width="250px; display: inline-block;" :options="tree" :props="defaultProps" /> -->
            <el-select v-model="form.deptId" size="small" placeholder="请选择单位" style="width:250px;" filterable clearable>
              <el-option v-for="item in tree" :label="item.companyName" :value="item.companyCode"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-row>
      <el-row>
        <el-button @click="reset" size="small" style="float:right; margin-left:10px;">重置</el-button>
        <el-button type="primary" icon="el-icon-search" size="small" style="float:right;" @click="listSearch">查询</el-button>
        <el-button type="primary" icon="el-icon-plus" size="small" @click="addNewStation">新增场站</el-button>
        <el-button type="primary" size="small" @click="uploadStationTemplate">模版下载</el-button>
        <el-button type="primary" size="small" icon="el-icon-upload2" @click="uploadStation">上传场站信息</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" @click="deleteStation">删除</el-button>
      </el-row>
    </el-card>
    <el-row style="margin-top:10px;">
      <el-table
       :data="tableData"
       tooltip-effect="dark"
       size="small"
       @selection-change="handleSelectionChange"
       stripe
       border
       v-loading="loading"
       style="width: 100%">
       <el-table-column
        type="selection"
        width="55">
      </el-table-column>
       <el-table-column
         label="序号"
         type="index"
         width="60"
         >
       </el-table-column>
       <el-table-column
         label="单位"
         show-overflow-tooltip
         width="250"
         >
         <template slot-scope="scope">
           <span style="color:#606266;">
             {{
               scope.row.companyCode && tree.find(item => item.companyCode === scope.row.companyCode) && tree.find(item => item.companyCode === scope.row.companyCode).companyName
             }}
           </span>
         </template>
       </el-table-column>
       <el-table-column
         prop="stationName"
         width="250"
         show-overflow-tooltip
         label="场站名称">
       </el-table-column>
       <el-table-column
         prop="stationAddress"
         width="300"
         show-overflow-tooltip
         label="场站地址">
       </el-table-column>
       <el-table-column
         prop="stationAdminName"
         width="250"
         show-overflow-tooltip
         label="负责人">
       </el-table-column>
       <el-table-column
         prop="stationAdminPhone"
         width="150"
         show-overflow-tooltip
         label="联系电话">
       </el-table-column>
       <el-table-column
         label="操作">
         <template slot-scope="scope">
           <span class="btn" @click="changeStation(scope.row)">修改</span>
         </template>
       </el-table-column>
     </el-table>
    </el-row>
    <el-row class='pagination'>
      <el-pagination
        background
        :current-page.sync="currentPage"
        :page-size="pageSize"
        @current-change="handleCurrentChange"
        layout="total, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <!-- @size-change="handleSizeChange"
       sizes,
      :page-sizes="[100, 200, 300, 400]" -->
    </el-row>
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="500px" @close="cancelSubmit">
      <el-form :model="newForm" ref="newStation" :rules="rules" label-width="85px" style="padding-left:50px;">
        <el-form-item label="单位名称:" prop="companyCode">
          <!-- <SelectTree ref="orgTree" v-model="newForm.companyCode" width="250px;" style="height:40px;" :options="tree" :props="defaultProps" /> -->
          <el-select v-model="newForm.companyCode" size="small" placeholder="请选择单位" style="width:250px;">
            <el-option v-for="item in tree" :label="item.companyName" :value="item.companyCode"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="场站名称:"  prop="stationName">
          <el-input v-model="newForm.stationName" size="small" placeholder="请输入场站名称" style="width:250px;"/>
        </el-form-item>
        <el-form-item label="场站编码:" prop="stationCode">
          <!-- <el-select v-model="newForm.stationCode" placeholder="请选择场站类型" style="width:250px;">
            <el-option label="光伏" value="1"></el-option>
            <el-option label="核能" value="2"></el-option>
          </el-select> -->
          <el-input v-model="newForm.stationCode" size="small" placeholder="请输入场站编码" style="width:250px;"/>
        </el-form-item>
        <el-form-item label="场站地址:" prop="stationAddress">
          <el-input v-model="newForm.stationAddress" size="small" placeholder="请输入场站地址" style="width:250px;"/>
        </el-form-item>
        <el-form-item label="负责人:" prop="stationAdminName">
          <el-input v-model="newForm.stationAdminName" size="small" placeholder="请输入场负责人姓名" style="width:250px;"/>
        </el-form-item>
        <el-form-item label="联系电话:" prop="stationAdminPhone">
          <el-input v-model="newForm.stationAdminPhone" size="small" placeholder="请输入场负责人电话" style="width:250px;"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSubmit" size="small">取 消</el-button>
        <el-button type="primary" @click="addSubmit" size="small">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="导入场站信息" :visible.sync="uploadDataVisible" width="500px"  @close="cancelUpload">
      <el-form :model="uploadForm" ref="uploadStation" label-width="85px" style="padding-left:50px;">
        <el-form-item label="单位名称:">
          <el-select v-model="uploadForm.companyCode" size="small" placeholder="请选择单位" style="width:250px;">
            <el-option v-for="item in tree" :label="item.companyName" :value="item.companyCode"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择文件:"  prop="name">
          <el-upload
            class="upload-demo"
            action="https://jsonplaceholder.typicode.com/posts/"
            :on-change="handleChange"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :file-list="fileList"
            :multiple="false"
            :show-file-list="false"
            :auto-upload="false">
            <!-- <el-button size="small" type="primary">选择文件</el-button>
            {{ file && file.name }} -->
            <el-input style="width:250px;" size="small" prefix-icon="el-icon-folder-add" placeholder="请选择文件" v-model="file && file.name"></el-input>
          </el-upload>
        </el-form-item>
        <!-- <el-form-item label="场站类型:">
          <el-radio-group v-model="uploadForm.type" size="small">
            <el-radio label="csv">csv</el-radio>
            <el-radio label="xlsx">xlsx</el-radio>
          </el-radio-group>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="uploadSubmit" size="small">确 定</el-button>
        <el-button @click="cancelUpload" size="small">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import stationApi from "../../../api/stations"
import SelectTree from '../../../components/SelectTree'
export default {
  name: "stations",
  components: {
    SelectTree
  },
  data() {
    var checkPhone = (rule, value, callback) => {
      let reg = /^[1][3-9][0-9]{9}$/
      if (!reg.test(value)) {
        callback(new Error('请输入负责人联系电话'));
      } else {
        callback()
      }
    }
    return {
      deptId: null,
      tree: [],
      form: {
        deptId: null
      },
      loading: false,
      newForm: {
        companyCode: null,
        stationName: '',
        stationAddress: '',
        stationAdminName: '',
        stationAdminPhone: ''
        // stationCode: ''
      },
      fileList: [],
      uploadForm: {
        // type: 'xlsx',
        companyCode: ''
      },
      file: null,
      title: '',
      total: 0,
      pageSize: 10,
      currentPage: 1,
      dialogFormVisible: false,
      uploadDataVisible: false,
      tableData: [
      ],
      defaultProps: {
        parent: 'pid',
        value: 'id',
        label: 'name',
        children: 'children'
      },
      selection: [],
      rules: {
        stationName: [
          { required: true, message: '请输入场站名称', trigger: 'blur' }
        ],
        stationAddress: [
          { required: true, message: '请输入场站地址', trigger: 'blur' }
        ],
        stationCode: [
          { required: true, message: '请选择场站类型', trigger: 'blur' }
        ],
        stationAdminName: [
          { required: true, message: '请输入负责人姓名', trigger: 'blur' }
        ],
        companyCode: [
          { required: true, message: '请选择所属单位', trigger: 'change' }
        ],
        stationAdminPhone: [
          { required: true, validator: checkPhone, trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getList()
    this.getCompanies()
  },
  methods: {
    cancelSubmit() {
      this.dialogFormVisible = false
      this.newForm = {
        companyCode: null,
        stationName: '',
        stationAddress: '',
        stationAdminName: '',
        stationAdminPhone: '',
        stationCode: ''
      }
    },
    cancelUpload() {
      this.uploadDataVisible = false
      this.uploadForm = {
        // type: 'xlsx',
        companyCode: ''
      }
      this.fileList = []
      this.file = null
    },
    uploadStationTemplate() {
      window.open('/bigdata-pv-backend/stationManage/stationInfo/downloadTemplate')
    },
    listSearch() {
      this.currentPage = 1
      // this.pageSize = 100
      this.getList()
    },
    getCompanies() {
      stationApi.getCompanyList().then(res => {
        if (res && res.data.code === 200) {
          this.tree = res.data.data
        }
      })
    },
    reset() {
      this.form.deptId = ''
      this.currePage = 1
      // this.pageSize = 100
      this.getList()
    },
    getList() {
      this.loading = true
      stationApi.getList({
        companyCode: this.form.deptId,
        page: this.currentPage,
        limit: this.pageSize
      }).then(res => {
        this.loading = false
        if (res && res.data.code === 200) {
          this.tableData = res.data.data.list
          this.total = res.data.data.totalCount
        } else {
          this.$message.error(res.data.message)
        }
      }).catch(err => {
        this.loading = false
      })
    },
    handleSelectionChange(selection) {
      this.selection = selection
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.currentPage = currentPage
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.getList()
    },
    addNewStation() {
      this.dialogFormVisible = true
      this.title = '新增场站'
    },
    handleChange(file, fileList) {
      this.file = file.raw
    },
    uploadStation() {
      this.uploadDataVisible = true
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList, 'handleRemove');
    },
    handlePreview(file) {
      console.log(file, 'handlePreview');
    },
    deleteStation() {
      if (this.selection.length === 0) {
        this.$message.error('请选择需要删除的场站')
        return
      }
      this.$confirm('是否确认删除选中场站', '确定', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        stationApi.deleteStation({
          ids: this.selection.map(item => item.id)
        }).then(res => {
          if (res && res.data.code === 200) {
            this.$message.success('删除场站成功')
            this.getList()
          } else {
            this.$message.error(res.data.message)
          }
        })
      }).catch(() => {
        console.log('取消删除')
      })
    },
    changeStation(data) {
      this.dialogFormVisible = true
      this.title = '修改场站信息'
      this.newForm = {
        companyCode: JSON.parse(JSON.stringify(data)).companyCode,
        stationName: JSON.parse(JSON.stringify(data)).stationName,
        stationAddress: JSON.parse(JSON.stringify(data)).stationAddress,
        stationAdminName: JSON.parse(JSON.stringify(data)).stationAdminName,
        stationAdminPhone: JSON.parse(JSON.stringify(data)).stationAdminPhone,
        stationCode: JSON.parse(JSON.stringify(data)).stationCode,
        id: JSON.parse(JSON.stringify(data)).id
      }
    },
    addSubmit() {
      this.$refs.newStation.validate((valid) => {
          if (valid) {
            if (this.title === '新增场站') {
              stationApi.addNewStation(this.newForm).then(res => {
                if (res && res.data.code === 200) {
                  this.$message.success('新增场站成功')
                  this.dialogFormVisible = false
                  this.newForm = {
                    companyCode: null,
                    stationName: '',
                    stationAddress: '',
                    stationAdminName: '',
                    stationAdminPhone: '',
                    stationCode: ''
                  }
                  this.getList()
                } else {
                  this.$message.error(res.data.message)
                }
              })
            } else {
              stationApi.updateStation(this.newForm).then(res => {
                if (res && res.data.code === 200) {
                  this.$message.success('修改场站信息成功')
                  this.dialogFormVisible = false
                  this.newForm = {
                    companyCode: null,
                    stationName: '',
                    stationAddress: '',
                    stationAdminName: '',
                    stationAdminPhone: '',
                    stationCode: ''
                  }
                  this.getList()
                } else {
                  this.$message.error(res.data.message)
                }
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
    },
    uploadSubmit() {
      if (!this.uploadForm.companyCode) {
        this.$message.error('请选择所属单位')
        return
      }
      if (!this.file) {
        this.$message.error('请选择上传文件')
        return
      }
      let formData = new FormData()
      formData.append('mfile', this.file);
      formData.append('companyCode', this.uploadForm.companyCode)
      stationApi.uploadStation(formData).then(res => {
        if (res && res.data.code === 200) {
          this.uploadForm = {
            // type: 'xlsx',
            companyCode: ''
          }
          this.file = null
          this.uploadDataVisible = false
          this.$message.success(res.data.message)
          this.getList()
        } else {
          this.$message.error(res.data.message)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .stations{
    padding:10px 20px;
    .searchLine{
      .searchItem{
        display: inline-block;
        width: 300px;
        vertical-align: top;
      }
      .el-form-item{
        margin-bottom: 5px !important;
      }
    }
    .btn{
      color:#409EFF;
      cursor: pointer;
    }
    .pagination{
      margin-top: 20px;
      text-align: center;
      .el-dialog__header{
        border-bottom: 1px solid #fff;
      }
      .el-form-item__content{
        height: 40px;
      }
      .dialog-footer{
        text-align: center;
      }
    }
  }


</style>
